package com.sunfeng.chap5.info;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Set;

public class Test1 {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("localhost",7777));
        serverSocketChannel.configureBlocking(false);

        ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();
        serverSocketChannel1.bind(new InetSocketAddress("localhost",8888));
        serverSocketChannel1.configureBlocking(false);
        final Selector selector = Selector.open();

        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        SelectionKey selectionKey1 = serverSocketChannel1.register(selector, SelectionKey.OP_ACCEPT);
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Socket socket7777 = new Socket("localhost", 7777);
                    OutputStream outputStream = socket7777.getOutputStream();
                    outputStream.write("我是中国人，我来自客户端77777".getBytes());
                    socket7777.close();


                    Socket socket8888 = new Socket("localhost", 8888);
                    OutputStream socket8888OutputStream = socket8888.getOutputStream();
                    socket8888OutputStream.write("我是中国人，我来自客户端8888".getBytes());
                    socket8888.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

        Thread getInfo = new Thread() {
            @Override
            public void run() {
                try {
                  Thread.sleep(10000);
                    System.out.println();
                    Set<SelectionKey> keys = selector.keys();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    System.out.println("执行后的第二次信息");
                    System.out.println(keys.size());
                    System.out.println(selectionKeys.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        getInfo.start();
        Thread.sleep(1000);



    }
}
